package com.kaiyidiannao.common.util;


import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.content.ComponentName;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.Toast;
import com.kaiyidiannao.main.R;

/**
 * Created by Administrator on 14-1-14.
 */
public class AppUtils {
    private static final int time = 2000;
    private static boolean clickFirst = false;
    private static Toast mToast;
    private static Handler myHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            clickFirst = false;
        }
    };
    public static int NETWORK_OK = 1; // 网络正常״̬
    public static int NETWORK_TIMEOUT = 2;
    public static int NETWORK__NOT_PREPARE = 3;
    public static int NETWORK_ERROR = 4;

    public static void exit(Activity activity) {

        if (clickFirst) {
            System.exit(0);
        } else {
            startProcessTiming();
            Toast.makeText(activity, R.string.click, Toast.LENGTH_SHORT).show();
        }

    }


    private static void startProcessTiming() {
        new Thread(new Runnable() {

            @Override
            public void run() {
                clickFirst = true;
                try {
                    Thread.sleep(time);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
                myHandler.sendEmptyMessage(0);
            }
        }).start();
    }

    // Toast Util
    public static void show(Context ctx, String text) {
        if (mToast == null) {
            mToast = Toast.makeText(ctx, text, Toast.LENGTH_SHORT);
        } else {
            mToast.setText(text);
        }
        mToast.show();
    }

    // 获取网络状态
    public static int getNetState(Context context) {
        try {
            ConnectivityManager connectivity = (ConnectivityManager) context
                    .getSystemService(Context.CONNECTIVITY_SERVICE);
            if (connectivity != null) {
                NetworkInfo networkinfo = connectivity.getActiveNetworkInfo();
                if (networkinfo != null) {
                    if (networkinfo.isAvailable() && networkinfo.isConnected()) {
                        return NETWORK_OK;
                    } else {
                        return NETWORK__NOT_PREPARE;
                    }
                }
            }
        } catch (Exception e) {
        }
        return NETWORK_ERROR;
    }


    /**
     * 获取SD卡状态
     *
     * @return
     */
    public static boolean isExistSD() {
        return Environment.getExternalStorageState().equals(
                Environment.MEDIA_MOUNTED);
    }

    /*
     * 打开设置网络界面
     */
    public static void setNetworkMethod(final Context context) {
        // 提示对话框
        Builder builder = new Builder(context);
        builder.setTitle(R.string.network)
                .setMessage(R.string.set_network)
                .setPositiveButton(R.string.set, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        Intent intent = null;

                        if (android.os.Build.VERSION.SDK_INT > 10) {
                            intent = new Intent(
                                    android.provider.Settings.ACTION_WIRELESS_SETTINGS);
                        } else {
                            intent = new Intent();
                            ComponentName component = new ComponentName(
                                    "com.android.settings",
                                    "com.android.settings.WirelessSettings");
                            intent.setComponent(component);
                            intent.setAction("android.intent.action.VIEW");
                        }
                        context.startActivity(intent);
                    }
                })
                .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                    }
                }).show();
    }


    /** 点击EditText以外的地方, 隐藏软键盘和功能选项
     *  eg:setupUI(findViewById(R.id.scrollview_smallnote));
     * @param view 该activity的根view
     * @param c
     */
    public static void setupUI(View view, final Activity c) {
        //Set up touch listener for non-text box views to hide keyboard.
        if(!(view instanceof EditText)) {

            view.setOnTouchListener(new View.OnTouchListener() {

                @Override
                public boolean onTouch(View v, MotionEvent event) {
                    hideKeyboard(c);
                    return false;
                }
            });
        }

        //If a layout container, iterate over children and seed recursion.
        if (view instanceof ViewGroup) {
            for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
                View innerView = ((ViewGroup) view).getChildAt(i);
                setupUI(innerView, c);
            }
        }
    }

    /**
     * 隐藏输入法面板
     */
    public static void hideKeyboard(Activity c) {
        InputMethodManager imm = ((InputMethodManager) c.getSystemService(c.INPUT_METHOD_SERVICE));
        if (imm != null && c.getCurrentFocus() != null) {
            imm.hideSoftInputFromWindow(c.getCurrentFocus().getWindowToken(),
                    InputMethodManager.HIDE_NOT_ALWAYS);
        }
    }

}
